package com.rt.code.utils.page;

import com.google.gson.Gson;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.Serializable;
import java.io.Writer;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Data
@ApiModel(description= "返回响应数据")
public class Result<T> implements Serializable{
	private static final long serialVersionUID = 1L;

	@ApiModelProperty(value = "返回List对象")
	private List<T> list = new ArrayList<T>();

	@ApiModelProperty(value = "返回泛型对象")
	private T obj = null;

	@ApiModelProperty(value = "返回Map对象")
	private Map<String,Object> map = new HashMap<String, Object>();

	@ApiModelProperty(value = "返回字符串对象")
	private String remark = "";

	private Boolean success = false;
	private Integer code = 0;
	private String content = "";
	private String contentOnly = "";

	public boolean isSuccess(){
		return success;
	}

	public Result success(String ... reasons){
		success = true;
		code = 1;

		if(reasons==null || reasons.length==0){
			content = "操作成功";
			contentOnly = "";
		}else{
			content = "操作成功："+reasons[0];
			contentOnly = reasons[0];
		}
		return this;
	}
	
	public Result fault(String ... reasons){
		success = false;
		code = 0;

		if(reasons==null || reasons.length==0){
			content = "操作失败";
			contentOnly = "";
		}else{
			content = "操作失败："+reasons[0];
			contentOnly = reasons[0];
		}
		return this;
	}

	public void response(HttpServletResponse response) throws IOException {
		response.setContentType("text/json;charset=utf-8");
		Writer out = response.getWriter();
		out.write(new Gson().toJson(this));
		out.flush();
		out.close();
	}

	@Override
	public String toString(){
		return new Gson().toJson(this);
	}


}
